const { Client } = require('pg');
const shp = require('shpjs');
const axios = require('axios');
let exec = require('child_process').exec;
module.exports = {    
    /**
     * 发布图层
     * @param {*} req 
     * @param {*} res 
     */
    async publishLayer(req, res){
        const geoserverWorkspaces = 'http://10.0.40.39:8814/geoserver/rest/workspaces';
        let namespace = "workspace_hello";
        let datastoresName = "drawGeometry";
        let shppname = "D:/road.zip"
        let shplen = shppname.split("/").length
        let shpname = shppname.split("/")[shplen - 1].split(".")[0]  //获取shp文件名
        //let mkspacestr = 'curl -v -u admin:geoserver -XPOST -H "Content-type: text/xml" -d "<workspace><name>' + namespace + '</name></workspace>" '+geoserverWorkspaces     //创建工作区的命令句子
        let publishShpStr = 'curl -v -u admin:geoserver -XPUT -H "Content-type: application/zip" --data-binary @' + shppname + ' '+geoserverWorkspaces+'/' + namespace + '/datastores/' + datastoresName + '/file.shp'
        exec(publishShpStr, function (err, stdout, stderr) {
            console.log('publish stder:'+  stderr);
            if (err) {                      
                console.log('publish error:' + stderr);
                return res.status(200).send({
                    success: false,
                    message: 'successful'
                })
            } else {

                console.log("publish new shapefile " + shpname + " success!")    //提示shapefile上传成功
                return res.status(200).send({
                    success: true,
                    message: 'successful'
                })
            }
        })

        // exec(mkspacestr, function (err, stdout, stderr) {
        //     console.log('mkspacestr publish stder======:'+  stderr);
        //     if (err) {

        //         console.log('make space error:' + stderr);

        //     } else {

        //         console.log("make new space " + namespace + " success!")    //提示工作区新增成功

        //         // 将影像文件路径名放入curl的put方法中发布影像
        //         exec(publishShpStr, function (err, stdout, stderr) {
        //             console.log('publish stder:'+  stderr);
        //             if (err) {                      
        //                 console.log('publish error:' + stderr);
        //                 return res.status(200).send({
        //                     success: false,
        //                     message: 'successful'
        //                 })
        //             } else {

        //                 console.log("publish new shapefile " + shpname + " success!")    //提示shapefile上传成功
        //                 return res.status(200).send({
        //                     success: true,
        //                     message: 'successful'
        //                 })
        //             }
        //         })
        //     }
        // });
    },

    /**
     * shp导入postgis
     * @param {*} req 
     * @param {*} res 
     * @returns 
     */
    async importShp(req, res) {     
        const postgisConnectionInfo = {
            user: 'postgres',
            password: 'archesadmin',
            host: '10.0.40.39',
            port: '5432',
            database: 'postgis_25_sample',
        };    
        //shp库要用http
        const shpFilePath = 'http://www.number2ai.com:8099/道路面_坐标正确.zip';

        // Table name  
        const tableName = 'ageo_road';
        const client = new Client(postgisConnectionInfo);
        client.connect();
        client.query(`CREATE TABLE ${tableName} (geom geometry);`, (err, res) => {
            //if (err) { throw err; }
            console.log("开始读取shp文件")
            const promise =  shp(shpFilePath); // 指定输入的SHP文件路径
            console.log("开始保存")
            promise.then(data=>{               
                for (let i = 0; i < data.features.length; i++) {
                    geojson ="ST_GeomFromGeoJSON('"+JSON.stringify(data.features[i].geometry)+"')"                 
                    client.query('INSERT INTO '+tableName+' (geom) VALUES ('+geojson+')');
                }
            })
            console.log("结束保存")
        })

        return res.status(200).send({
            success: true,
            message: 'successful'
        })
    }
}